package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import fdoj.eventInvitations.dao.ContactDao;
import fdoj.eventInvitations.dao.EventDao;
import fdoj.eventInvitations.dao.InvantationDao;
import fdoj.eventInvitations.entity.Comment;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Invantation;
import fdoj.eventInvitations.entity.Person;
import fdoj.eventInvitations.entity.Response;

public class HomeController extends HttpServlet{
	@EJB
	private EventDao eventDao;
	@EJB
	private ContactDao contactDao;
	@EJB
	private InvantationDao invitationDao;
	private HttpSession session;
	private Person loggedUser;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			session = request.getSession();
			loggedUser = (Person) session.getAttribute("loggedUser");
			if(loggedUser == null){
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
			
			List<Invantation> invitations=invitationDao.invitationByReceiver(loggedUser.getEmail());
			for(Invantation i:invitations){
				if(i.getStatus().equals(Response.NON_RESPONSE)){
					i.setStatus(Response.VISITED_PAGE);
					invitationDao.merge(i);
				}
			}
			List<Event> evs= eventDao.invitedByMail(loggedUser.getEmail());
			for(Event e:evs){
				e.setAttending(contactDao.contactsByEvent(e.getId(), Response.CONFIRMED));
				e.setNotAttending(contactDao.contactsByEvent(e.getId(), Response.DECLINED));
				e.setMaybeAttending(contactDao.contactsByEvent(e.getId(), Response.VISITED_PAGE));
				e.setUnanswered(contactDao.contactsByEvent(e.getId(), Response.NON_RESPONSE));
			}
			session.setAttribute("callToIvents", evs);
			
			List<Event> events=eventDao.eventByMaker(loggedUser.getId());
			
			for(Event e : events){
				e.setAttending(contactDao.contactsByEvent(e.getId(), Response.CONFIRMED));
				e.setNotAttending(contactDao.contactsByEvent(e.getId(), Response.DECLINED));
				e.setMaybeAttending(contactDao.contactsByEvent(e.getId(), Response.VISITED_PAGE));
				e.setUnanswered(contactDao.contactsByEvent(e.getId(), Response.NON_RESPONSE));
			}
			
			session.setAttribute("events", events);
			session.setAttribute("now", new Date());
			request.getRequestDispatcher("/home.jsp").forward(request, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();

		}
		response.sendRedirect(response.encodeRedirectURL("./error.jsp"));
	}
}
